package com.xinlan.imageeditlibrary.editimage.utils;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.drawable.BitmapDrawable;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.app.AppCompatDialog;

import com.baselibrary.utils.CommonUtil;
import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiskCache;
import com.nostra13.universalimageloader.cache.disc.naming.HashCodeFileNameGenerator;
import com.nostra13.universalimageloader.cache.memory.impl.LruMemoryCache;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.nostra13.universalimageloader.core.decode.BaseImageDecoder;
import com.nostra13.universalimageloader.core.download.BaseImageDownloader;
import com.nostra13.universalimageloader.utils.StorageUtils;
import com.xinlan.imageeditlibrary.BaseEditFragment;
import com.xinlan.imageeditlibrary.R;
import com.xinlan.imageeditlibrary.editimage.fragment.AddTextFragment;
import com.xinlan.imageeditlibrary.editimage.fragment.StickerFragment;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

public class BaseUtils extends AppCompatActivity {
    private static Map<String, BaseEditFragment> fragmentList = new HashMap<>();

    /**
     * 检测图片载入框架是否导入  若没有 则导入并初始化
     */
    public static void checkInitImageLoader(Activity activity) {
        if (!ImageLoader.getInstance().isInited()) {
            initImageLoader(activity);
        }//end if
    }

    /**
     * 初始化图片载入框架
     */
    public static void initImageLoader(Activity activity) {
        File cacheDir = StorageUtils.getCacheDirectory(activity);
        int MAXMEMONRY = (int) (Runtime.getRuntime().maxMemory());
        // System.out.println("dsa-->"+MAXMEMONRY+"   "+(MAXMEMONRY/5));//.memoryCache(new
        // LruMemoryCache(50 * 1024 * 1024))
        DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
                .cacheInMemory(true)
                .cacheOnDisk(true)
                .build();
        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
                activity).memoryCacheExtraOptions(480, 800).defaultDisplayImageOptions(defaultOptions)
                .diskCacheExtraOptions(480, 800, null).threadPoolSize(3)
                .threadPriority(Thread.NORM_PRIORITY - 2)
                .tasksProcessingOrder(QueueProcessingType.FIFO)
                .denyCacheImageMultipleSizesInMemory()
                .memoryCache(new LruMemoryCache(MAXMEMONRY / 5))
                .diskCache(new UnlimitedDiskCache(cacheDir))
                .diskCacheFileNameGenerator(new HashCodeFileNameGenerator()) // default
                .imageDownloader(new BaseImageDownloader(activity)) // default
                .imageDecoder(new BaseImageDecoder(false)) // default
                .defaultDisplayImageOptions(DisplayImageOptions.createSimple()).build();

        ImageLoader.getInstance().init(config);
    }

    public static Dialog getLoadingDialog(Context context, int titleId,
                                          boolean canCancel) {
        return getLoadingDialog(context, context.getString(titleId), canCancel);
    }

    public static Dialog getLoadingDialog(Activity act) {
        AppCompatDialog appCompatDialog = new AppCompatDialog(act, com.baselibrary.R.style.LoadingDialogTheme);
        @SuppressLint("InflateParams")
        View view = act.getLayoutInflater().inflate(com.baselibrary.R.layout.web_layout_loading, null);
        appCompatDialog.setContentView(view);
        TextView title = view.findViewById(com.baselibrary.R.id.content);
        ImageView progress = view.findViewById(com.baselibrary.R.id.progress);
        Animation antv = AnimationUtils.loadAnimation(act, com.baselibrary.R.anim.loading_progressbar);
        LinearInterpolator lin = new LinearInterpolator();
        antv.setInterpolator(lin);
        antv.setRepeatCount(-1);
        progress.startAnimation(antv);
        appCompatDialog.setCanceledOnTouchOutside(false);
        return appCompatDialog;
    }

    public static Dialog getLoadingDialog(Context context, String title,
                                          boolean canCancel) {
        ProgressDialog dialog = new ProgressDialog(context);
        dialog.setCancelable(canCancel);
        dialog.setMessage(title);
        return dialog;
    }

    /**
     * 保存上一步的状态
     *
     * @param mLasFragment
     */
    public static void retainAction(BaseEditFragment mLasFragment) {
        if (mLasFragment == null)
            return;
//        if (mLasFragment instanceof CropFragment) {
//            ((CropFragment) mLasFragment).applyCropImage(false);
//        } else if (mLasFragment instanceof FilterListFragment) {
//            ((FilterListFragment) mLasFragment).applyFilterImage(false);
//        } else if (mLasFragment instanceof PaintFragment) {
//            ((PaintFragment) mLasFragment).savePaintImage(false);
//        } else if (mLasFragment instanceof StickerFragment) {
//            ((StickerFragment) mLasFragment).applyStickers(false);
//        } else if (mLasFragment instanceof AddTextFragment) {
//            ((AddTextFragment) mLasFragment).applyTextImage(false);
//        }
    }

    public static PopupWindow showPopwindow(final Activity activity,
                                            View contentView,
                                            int width,
                                            int height) {


        PopupWindow popupWindow = new PopupWindow(contentView,
                width,
                height);
        popupWindow.setFocusable(true);// 取得焦点
        //注意  要是点击外部空白处弹框消息  那么必须给弹框设置一个背景色  不然是不起作用的
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        //点击外部消失
        popupWindow.setOutsideTouchable(true);
        //设置可以点击
        popupWindow.setTouchable(true);
        //进入退出的动画，指定刚才定义的style
        popupWindow.setAnimationStyle(R.style.camera_popwindow_anim_style);
        return popupWindow;
    }

    public static PopupWindow showPaintPop(final Activity activity,
                                                   View contentView,
                                                   int width,
                                                   int height) {


        PopupWindow popupWindow = new PopupWindow(contentView,
                width,
                height);
        popupWindow.setFocusable(false);// 取得焦点
        //注意  要是点击外部空白处弹框消息  那么必须给弹框设置一个背景色  不然是不起作用的
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        //点击外部消失
        popupWindow.setOutsideTouchable(false);
        //设置可以点击
        popupWindow.setTouchable(true);
        //进入退出的动画，指定刚才定义的style
        popupWindow.setAnimationStyle(R.style.camera_popwindow_anim_style);
        return popupWindow;
    }


    public static void addStickerAndText(final AddTextFragment mAddTextFragment, StickerFragment mStickerFragment, final OnAddStickerAndText onAddStickerAndText) {
        if (mStickerFragment != null) {
            mStickerFragment.applyStickers(true, new OnAddStickerAndText() {
                @Override
                public void onAddStickerAndText(int count) {
                    if (mAddTextFragment != null)
                        mAddTextFragment.applyTextImage(onAddStickerAndText);
                }
            });
        }
    }

    public static int getScreenHeight(Context context) {
        if (context != null) {
            WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
            DisplayMetrics dm = new DisplayMetrics();
            wm.getDefaultDisplay().getMetrics(dm);
            return dm.heightPixels;       // 屏幕高度（像素）
        }else{
            return 0;
        }
    }

    public static int getScreenWidth(Context context) {
        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics dm = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(dm);
        return dm.widthPixels;
    }

    public interface OnAddStickerAndText {
        void onAddStickerAndText(int count);
    }

}//end class
